<?

Yii::import('application.modules.user.controllers.YumController');
Yii::import('application.modules.user.models.*');
Yii::import('application.modules.profile.models.*');

class YumProfileController extends YumController {
	public $_model;

	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index', 'admin', 'visits'),
				'expression' => 'Yii::app()->user->isAdmin()'
				),
			array('allow',
				'actions'=>array('view', 'update', 'edit','subscribe','unSubscribe','like','dislike'),
				'users' => array('@'),
				),
			array('allow',
				'actions'=>array('profile','Notfound'),
				'users' => array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionUpdate($id = null) {
		if(!$id)
			$id = Yii::app()->user->id;

		$user = $this->loadModel($id);
		$profile = $user->profile;

		if(isset($_POST['YumUser']) || isset($_POST['YumProfile'])) {
			$user->attributes=@$_POST['YumUser'];
			$profile->attributes = @$_POST['YumProfile'];
			$profile->user_id = $user->id;


			$profile->validate();
			$user->validate();

			if(!$user->hasErrors() && !$profile->hasErrors()) {
				if($user->save() && $profile->save()) {
					Yii::app()->user->setFlash('success', '个人资料修改成功！');
					$this->redirect(array('/profile/profile/update'));
				}
			}
		}

		if(Yii::app()->request->isAjaxRequest)
			$this->renderPartial(Yum::module('profile')->profileEditView,array(
						'user'=>$user,
						'profile'=>$profile,
						));
		else
			$this->render(Yum::module('profile')->profileEditView,array(
						'user'=>$user,
						'profile'=>$profile,
						));
	}

	public function actionVisits() {
		$this->layout = Yum::module()->adminLayout;

		$this->render('visits',array(
			'model'=>new YumProfileVisit(),
		));

	}

	public function beforeAction($action) {
		if(!isset($this->layout))
			$this->layout = Yum::module('profile')->layout;
		return parent::beforeAction($action);
	}

	public function loadModel($id = null) {
		if(!$id)
			$id = Yii::app()->user->id;

		if(is_numeric($id))
			return $this->_model = YumUser::model()->findByPk($id);
		else if(is_string($id))
			return $this->_model = YumUser::model()->find("username = '{$id}'");
	}

	
	public function actionProfile($nick = null) {

		/*if(!Yum::module('profile')->profilesViewableByGuests && Yii::app()->user->isGuest)
			throw new CHttpException(403);
		*/
		// If no profile id is provided, take myself
		
		if(!$nick){
			$id = Yii::app()->user->id;
		}else{
			$id = Yii::app()->user -> getIdByName($nick);
		}
		
		if(!$id){
			$this -> run('notfound');
		}else{
			
			//如果是教育家 教育家的个人主页
			if(Yii::app()->user -> isEdu){
				$this->eduProfile($id);
			}else{
			//如果是用户 用户的个人主页
				$this->userProfile($id);
			}
		}
	
	}
	
	/**
	 * 
	 * @param unknown_type $edu_id
	 */
	private function eduProfile($edu_id){
		
		
		$audio_model= Audios::model();
		$audio = $audio_model -> getAudioByEduer($edu_id);
		
		//历史播放记录
		$history_cdbcriteria = new CDbCriteria();
		$history_cdbcriteria -> compare('history_from', $edu_id);
		$history_cdbcriteria -> limit =  10;
		$history_cdbcriteria -> order = "dateline desc";
		$history = AudioHistory::model() ->with('audios')->findAll($history_cdbcriteria);
			
			
		$view = Yum::module('profile')->profileView;
		$this->loadModel($edu_id);
		$this->updateVisitor(Yii::app()->user->id, $edu_id);
			
		$AudiodataProvider=new CActiveDataProvider('Audios');
			
		if(Yii::app()->request->isAjaxRequest){
			$this->renderPartial($view, array('model' => $this->_model,'history_model'=>$history), false, true);
		}
		else{
			$this->render($view, array('model' => $this->_model,'history_model'=>$history), false, true);
		}
		
	} 
	
	/**
	 * 
	 * @param unknown_type $edu_id
	 */
	private function userProfile($user_id){
		
		//历史播放记录
		$history_cdbcriteria = new CDbCriteria();
		$history_cdbcriteria -> compare('history_from', $user_id);
		$history_cdbcriteria -> limit =  10;
		$history_cdbcriteria -> order = "dateline desc";
		$history = AudioHistory::model() ->with('audios')->findAll($history_cdbcriteria);
			
			
		$view = Yum::module('profile')->profileView;
		$this->loadModel($user_id);
		$this->updateVisitor(Yii::app()->user->id, $user_id);
			
		$AudiodataProvider=new CActiveDataProvider('Audios');
			
		if(Yii::app()->request->isAjaxRequest){
			$this->renderPartial($view, array('model' => $this->_model,'history_model'=>$history), false, true);
		}
		else{
			$this->render($view, array('model' => $this->_model,'history_model'=>$history), false, true);
		}
	}
	
	/**
	 * 订阅教育家
	 * @param unknown_type $nick
	 */
	public function actionSubscribe($nick){
		
		$eduid = Yii::app()->user -> getIdByName($nick);
		if($eduid){
			//找到教育家
			if(Educators::model()->canSubscribe($eduid)){
				Educators::model()->setSubscribe($eduid);
				//success subscribe
				echo CJavaScript::jsonEncode(array('code'=>200,'msg'=>'订阅成功!'));
			}else{
				echo CJavaScript::jsonEncode(array('code'=>222,'msg'=>'您已经订阅成功!'));
			}
		}else{
			//未找到教育家
			echo CJavaScript::jsonEncode(array('code'=>404,'msg'=>'没有找到相关的教育家!'));
		}
	}
	
	/**
	 * 取消订阅教育家
	 * @param unknown_type $nick
	 */
	public function actionUnSubscribe($nick){
		$eduid = Yii::app()->user -> getIdByName($nick);
		if($eduid){
			// an unsubscribe
			if(!Educators::model()->canSubscribe($eduid)){
				Educators::model()->setUnSubscribe($eduid);
				//success unsubscribe
				echo CJavaScript::jsonEncode(array('code'=>200,'msg'=>'取消订阅成功!'));
			}else{
				echo CJavaScript::jsonEncode(array('code'=>222,'msg'=>'您取消订阅!'));
			}
		}else{
			//未找到教育家
			echo CJavaScript::jsonEncode(array('code'=>404,'msg'=>'没有找到相关的教育家!'));
		}
	}
	
	/**
	 * 赞教育家
	 * @param unknown_type $nick
	 */
	public function actionLike($nick){
		
		$eduid = Yii::app()->user -> getIdByName($nick);
		if($eduid){
			//找到教育家
			if(Educators::model()->canLike($eduid)){
				Educators::model()->setLike($eduid);
				//success subscribe
				echo CJavaScript::jsonEncode(array('code'=>200,'msg'=>'赞成功!'));
			}else{
				echo CJavaScript::jsonEncode(array('code'=>222,'msg'=>'您已经赞成功!'));
			}
		}else{
			//未找到教育家
			echo CJavaScript::jsonEncode(array('code'=>404,'msg'=>'没有找到相关的教育家!'));
		}
	}
	
	/**
	 * 取消赞教育家
	 * @param unknown_type $nick
	 */
	public function actionDislike($nick){
	
		$eduid = Yii::app()->user -> getIdByName($nick);
		if($eduid){
			//找到教育家
			if(!Educators::model()->canLike($eduid)){
				Educators::model()->setDislike($eduid);
				//success subscribe
				echo CJavaScript::jsonEncode(array('code'=>200,'msg'=>'取消赞成功!'));
			}else{
				echo CJavaScript::jsonEncode(array('code'=>222,'msg'=>'您已经取消赞!'));
			}
		}else{
			//未找到教育家
			echo CJavaScript::jsonEncode(array('code'=>404,'msg'=>'没有找到相关的教育家!'));
		}
	}
	
	
	public function actionNotfound(){
		$this -> render('notfound');
	}
	
	public function actionView($id = null) {
		if(!Yum::module('profile')->profilesViewableByGuests && Yii::app()->user->isGuest)
			throw new CHttpException(403);

		// If no profile id is provided, take myself
		if(!$id)
			$id = Yii::app()->user->id;

		$view = Yum::module('profile')->profileView;

		$this->loadModel($id);
		$this->updateVisitor(Yii::app()->user->id, $id);
		
		$history_model = AudioHistory::model();
		$history_model -> history_from = $id;
		$history_model = $history_model -> search() -> data;

		
		if(Yii::app()->request->isAjaxRequest)
			$this->renderPartial($view, array('model' => $this->_model,'history_model'=>$history_model), false, true);
		else
			$this->render($view, array('model' => $this->_model,'history_model'=>$history_model), false, true);

	}

	public function updateVisitor($visitor_id, $visited_id) {
		if(!Yum::module('profile')->enableProfileVisitLogging)
			return false;

		// If the user does not want to log his profile visits, cancel here
		if(Yum::module('profile')->enableProfileVisitLogging
				&& isset(Yii::app()->user->data()->privacy) 
				&& !Yii::app()->user->data()->privacy->log_profile_visits)
			return false;
			
		// Visiting my own profile doesn't count as visit
		if($visitor_id == $visited_id)
			return true;

		$visit = YumProfileVisit::model()->find(
				'visitor_id = :visitor_id and visited_id = :visited_id', array(
					':visitor_id' => $visitor_id,
					':visited_id' => $visited_id));
		if($visit) {
			$visit->save();
		} else {
			$visit = new YumProfileVisit();
			$visit->visitor_id = $visitor_id;
			$visit->visited_id = $visited_id;
			$visit->save();
		}
	}

	public function actionIndex()
	{
		/*if(Yii::app()->user->isAdmin())
			$this->actionAdmin();
		else*/
		//$this->redirect('view');
		$this -> run('profile');
	}

	public function actionAdmin()
	{
		$this->layout = Yum::module()->adminLayout;
		$model = new YumProfile;

		$dataProvider=new CActiveDataProvider('YumProfile', array(
			'pagination'=>array(
				'pageSize'=>Yum::module()->pageSize,
			),
			'sort'=>array(
				'defaultOrder'=>'id',
			),
		));

		$this->render('admin',array(
			'dataProvider'=>$dataProvider,'model'=>$model,
		));
	}
}
